from pattern.circuit import Control


class entry(Control):

    JOIN_MSG = ":%(username)s!%(user)s JOIN :%(channel)s"
    NAMES_RPL = ":%(servername)s 353 %(username)s = %(channel)s :%(userlist)s\r\n:%(servername)s 366 %(username)s %(channel)s :End of /NAMES list.\r\n"

    def incoming(self, event):
        channels = event.data[0][0].split(",")
        username = event.trail.username
        self.onJoin(event, channels, username)
        for channel in channels:
            users = " ".join(self.listMembers(event, channel))
            info = {'channel': channel, 'username': username,
                       'user': username + "!here",
                       'userlist': users,
                       'servername': "localhost"}
            event.trail.wfile.write(self.NAMES_RPL % info)

    def onJoin(self, event, channels, username):
        bridge = self.acquireInterface(event, "onJoin")
        if bridge is not None:
            bridge.push("join", channels, username)


    def listMembers(self, event, channel):
        bridge = self.acquireInterface(event, "onJoin")
        if bridge is not None:
            return bridge.pull().get(channel, [])
